/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.cfg.serial;

import cn.easyplatform.studio.cfg.IdGenerator;
import cn.easyplatform.studio.dos.SerialDo;
import cn.easyplatform.studio.interceptor.CommandContext;

import java.util.HashMap;
import java.util.Map;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class StdIdGenerator implements IdGenerator {

	private static Map<String, SerialDo> keyMap;

	private static final int POOL_SIZE = 10;

	private CommandContext cc;

	@SuppressWarnings("unchecked")
	StdIdGenerator(CommandContext cc) {
		this.cc = cc;
		keyMap = (Map<String, SerialDo>) cc.getAppAttribute("ep_seq_generator");
		if (keyMap == null) {
			keyMap = new HashMap<String, SerialDo>();
			cc.setAppAttribute("ep_seq_generator", keyMap);
		}
	}

	@Override
	public Long getNextId(String name) {
		SerialDo sn = null;
		synchronized (keyMap) {
			if (keyMap.containsKey(name)) {
				sn = keyMap.get(name);
			} else {
				sn = new SerialDo(name, POOL_SIZE);
				keyMap.put(name, sn);
			}
		}
		return cc.getSeqDao().nextval(sn);
	}

}
